<?php

App::uses('AppController', 'Controller');

class EventsController extends AppController {
    
    public $uses = array ('Event', 'Function', 'Repertoire');
    
    public $paginate = array(
        'limit' => ITEMS_PER_PAGE,
        'order' => array(
            'Event.date' => 'desc'
        )
    );
    
    public function index() {
        $this->set('events', $this->paginate('Event', array(
            'OR' => array('Event.parent_id IS NULL', 'Event.parent_id'=>0)
        )));
    }
    
    protected function _setCommonData() {
        $this->set('eventTypes', array(
            'concert' => __('concert'),
            'journey' => __('journey'),
            'meeting' => __('meeting'),
            'other'   => __('other')
        ));
        
        $members = $this->Event->Member->find('all', array(
            'fields'    => array('Member.id', 'Member.name', 'Member.voice'),
            'recursive' => 0
        ));
        
        $allMembers = Set::combine($members, '{n}.Member.id', '{n}.Member.name');
        $this->set('allMembers', $allMembers);
        
        $allMembersByVoice = array();
        foreach ($members as $member) {
            $id    = $member['Member']['id'];
            $name  = $member['Member']['name'];
            $voice = $member['Member']['voice'];
            
            if (empty($allMembersByVoice[$voice])) {
                $allMembersByVoice[$voice] = array();
            }
            $allMembersByVoice[$voice][$id] = $name;
        }
        $this->set('allMembersByVoice', $allMembersByVoice);
        
        $this->set('allGuests', $this->Event->Guest->find('list', array(
            'fields' => array('Guest.id', 'Guest.name')
        )));
        
        $this->set('conductors', $this->Event->Member->find('list', array(
            'fields' => array('Member.id', 'Member.name'),
            'joins' => array(
                array(
                    'table' => 'members_functions',
                    'alias' => 'MemberChoirFunction',
                    'type'  => 'INNER',
                    'conditions' => array('MemberChoirFunction.member_id=Member.id')
                )
            ),
            'conditions' => array('MemberChoirFunction.function_id'=>array(3,4,5,6))
        )));
        
        preg_match_all('/\'(.*?)\'/', $this->Event->Member->_schema['voice']['type'], $voices);
        $this->set('voices', $voices[1]);
        $this->set('repertoire', $this->Repertoire->find('list'));

        $functions = $this->Function->find('list');
        foreach ($functions as &$func) {
            $func = __($func);
        }
        $this->set('allFunctions', $functions);
    }
    
    public function create() {
        $data = $this->Event->create();
        
        $this->_setCommonData();
        $this->set(compact('data'));
        $this->render('form');
    }
    
    public function edit($id) {
        $data = $this->Event->findById($id);
        
        $membersByVoice = array();
        foreach ($data['Member'] as $member) {
            $voice = $member['voice'];
            if (empty($membersByVoice[$voice])) {
                $membersByVoice[$voice] = array();
            }
            $membersByVoice[$voice][$member['id']] = $member['name'];
        }
    
        $this->_setCommonData();
        $this->set(compact('data', 'membersByVoice'));
        $this->render('form');
    }

    public function stampa($id) {
        $this->layout = 'print';
        $data = $this->Event->findById($id);
        
        $membersByVoice = array();
        foreach ($data['Member'] as $member) {
            $voice = $member['voice'];
            if (empty($membersByVoice[$voice])) {
                $membersByVoice[$voice] = array();
            }
            $membersByVoice[$voice][$member['id']] = $member['name'];
        }
    
        $this->_setCommonData();
        $this->set(compact('data', 'membersByVoice'));
        $this->render('print');
    }
    
    public function save() {
        $data = $this->data;
        if (! empty($data)) {
            $this->Event->create($data);
            
            if (! $this->Event->validates()) {
                $this->setFlash(strtotitle(__('save failed')) . ". " . strtotitle(__('invalid data')) . ".");
				$this->set("data",$data);
				$this->_setCommonData();
				return $this->render('form');
            }
            
            $data = $this->Event->refactorData($data);
            $this->Event->deleteRelationsData();
            
            
            if (! $this->Event->saveAll($data)) {
                $this->setFlash(strtotitle(__('save failed')) . ".");
                $this->set("data",$data);
                $this->_setCommonData();
                return $this->render('form');
            }
            
            $files = Set::extract('Chronicle.{n}.newFile', $data);
            foreach ($files as $file) {
                if (! $file['error']) {
                    upload($file['tmp_name'], implode(DS, array('img', 'chronicles', $this->Event->id, $file['name'])));
                }
            }
            $this->Event->removeOldFiles();
            
            $this->setFlash(strtotitle(__('saved')) . ".", 'ok');
            $this->redirect('edit/' . $this->Event->id);
        }
        
        $this->redirect('index');
    }
    
    public function parents($eventId=null) {
        $this->autoRender = false;
        $kword = $this->params->query['term'];
        
        $conditions = array(
            'Event.name LIKE' => "%{$kword}%"
        );
        if ($eventId) {
            $conditions['Event.id !='] = $eventId;
        }
        
        $data = $this->Event->find('all', array(
            'fields'     => array('Event.id', 'Event.name', 'Event.start', 'Event.end'),
            'conditions' => $conditions,
            'recursive'  => 0
        ));
        $arr = array();
        if ($data) {
            foreach ($data as $row) {
                $id  = $row['Event']['id'];
                $lbl = $row['Event']['name'] . ' (' . date_local($row['Event']['start']);
                if ($row['Event']['end']) {
                    $lbl .= ' - ' . date_local($row['Event']['end']);
                }
                $lbl .= ')';
                
                $arr[] = array(
                    'id'    => $id,
                    'label' => $lbl
                );
            }
        }
        
        echo json_encode($arr);
    }
    
    public function delete($id) {
        if ($this->Event->delete($id)) {
            $this->setFlash(__('deleted').".", 'ok');
        } else {
            $this->setFlash(__('delete failed').".");
        }
        $this->redirect('index');
    }
    
    public function singers($id) {
        $this->title = strtotitle(__('singers list'));
        $this->layout =  'blank';
        
        $event = $this->Event->findById($id);
        $this->Event->groupByVoice($event);
        
        $this->set('event', $event);
    }
    
    public function travellers($id) {
        $this->title = strtotitle(__('travellers list'));
        $this->layout =  'blank';
    
        $event = $this->Event->findById($id);
        $event['EventConductor'] = $this->Event->Member->findById($event['EventConductor']['id']);
        
        foreach ($event['Member'] as &$member) {
            $member['MemberContact'] = $this->Event->Member->MemberContact->findAllByMemberId($member['id']);
        }
        
        $this->set('event', $event);
    }
    
}
